#!/usr/bin/env python3
# -*- coding: utf-8 -*-


'''
爱听音乐爬虫
http://www.sfac.xyz/iting/song/2264
'''

import requests;
import os;
from datetime import datetime;

headers_sfac={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0",
    "Token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwicm9sZSI6IkFkbWluIiwidXNlckltYWdlIjoiaHR0cDovL3d3dy5zZmFjLnh5ejo4MDAwL2ltYWdlcy9wcm9maWxlLzE2ODg3MTE5MjI0NDkuanBnIiwiaWQiOjEsImV4cCI6MTY5MzM2NzMxNiwidXNlck5hbWUiOiJhZG1pbiIsImlhdCI6MTY5MzI4MDkxNn0.ND2M1Iu19w2x0V_-TLTeBjF1jk80HQYdBAkT2fsEMeM"
}
domain = "http://www.sfac.xyz:8000";

def get_audio_data(url):
    print(url);

    # 向目标网址发送请求，获得响应
    r = requests.get(url, headers=headers_sfac);
    # 根据响应状态做处理
    if r.status_code == 200:
        # 设置响应编码
        r.encoding = r.apparent_encoding;
        print(r.json());

        cover = domain + r.json().get("cover");
        url = domain + r.json().get("url");

        print(cover);
        print(url);

        os.makedirs("/temp", exist_ok=True);

        r_cover = requests.get(cover);
        if r_cover.status_code == 200:
            cover_content = r_cover.content;
            cover_name = str(datetime.now().timestamp()).replace(".", "") + ".jpg";
            with open(file = "/temp/" + cover_name, mode="wb") as f:
                f.write(cover_content);

        r_url = requests.get(url);
        if r_url.status_code == 200:
            url_content = r_url.content;
            url_name = str(datetime.now().timestamp()).replace(".", "") + ".mp3";
            with open(file = "/temp/" + url_name, mode="wb") as f:
                f.write(url_content);

if __name__ == '__main__':
    url = "http://538b537e25.zicp.vip:13595/api/resource/audio/2264/1";
    get_audio_data(url);

